package fg.sprite;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

public class Sprite {

	protected float x = 0f; // x coordinate
	protected float y = 0f; // y coordinate
	protected float w2 = 0f; // half width
	protected float h2 = 0f; // half height
	protected float angle = 0f; // rotation angle
	protected Image image; // image to draw
	protected float pivotX = 0f; // rotation point-x
	protected float pivotY = 0f; // rotation point-y

	public Sprite(String ref) throws SlickException {
		setImage(new Image(ref));
	}

	public Sprite(Image image) {
		setImage(image);
	}

	public void render(Graphics g) {
		float rx = x + pivotX;
		float ry = y + pivotY;
		g.rotate(rx, ry, angle);
		image.draw(x, y);
		g.rotate(rx, ry, -angle);
	}
	
	public void render(Graphics g, float x, float y) {
		float rx = x + pivotX;
		float ry = y + pivotY;
		g.rotate(rx, ry, angle);
		image.draw(x, y);
		g.rotate(rx, ry, -angle);
	}

	public void renderCentered(Graphics g) {
		image.draw(x - w2, y - h2);
	}
	
	public void renderCentered(Graphics g, float x, float y) {
		image.draw(x - w2, y - h2);
	}

	/**
	 * Rotates this Sprite amount the given angle in degrees (0 - 360). The
	 * value is automatically clamped in range.
	 * 
	 * @param amount
	 */
	public void rotate(float amount) {
		angle = (angle + amount) % 360f;
	}

	/**
	 * @return the x
	 */
	public float getX() {
		return x;
	}

	/**
	 * @param x
	 *            the x to set
	 */
	public void setX(float x) {
		this.x = x;
	}

	/**
	 * @return the y
	 */
	public float getY() {
		return y;
	}

	/**
	 * @param y
	 *            the y to set
	 */
	public void setY(float y) {
		this.y = y;
	}

	/**
	 * @return the angle
	 */
	public float getAngle() {
		return angle;
	}

	/**
	 * @param angle
	 *            the angle to set
	 */
	public void setAngle(float angle) {
		this.angle = angle;
	}

	/**
	 * @return the image
	 */
	public Image getImage() {
		return image;
	}

	/**
	 * @param image
	 *            the image to set
	 */
	public void setImage(Image image) {
		this.image = image;
		this.w2 = ((float) image.getWidth()) * 0.5f;
		this.h2 = ((float) image.getHeight()) * 0.5f;
	}

	/**
	 * @param x
	 * @param y
	 */
	public void setPosition(float x, float y) {
		this.x = x;
		this.y = y;
	}

	/**
	 * Set the pivot point to this sprites position. The pivot point is the
	 * relative position of this Sprites rotation point. 0, 0 means upper left.
	 * 
	 * @param px
	 * @param py
	 */
	public void setPivotPoint(float px, float py) {
		pivotX = px;
		pivotY = py;
	}
}
